package com.zhouyibike.uu.ui.activity.hehuoren;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.Cityselectbean;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.ProductPayTypeResult;
import com.zhouyibike.uu.entity.YiBuyBicycleResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.CityoActivity;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.adapter.BuydanchetypeAdapter2;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.MyGridListView;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.TextUtils;
//import com.zhy.view.flowlayout.MTagAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class ChengshihehuorenbuybikeActivity extends BaseActivity implements View.OnClickListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle, total_pricetv, textView2,tv_agreement;
    private ProductPayTypeResult chuandiProductPayTypeResult;
    private double moneycount = 0;
    private int yiquancount = 0;
    private BuydanchetypeAdapter2 adapter2;
    private ArrayList<ProductPayTypeResult.DataBean.PayTypesBean> payTypeslist = new ArrayList<>();
    private MyGridListView gv;
    private RelativeLayout xuanzechengshily;
    private ArrayList<Cityselectbean> citylistall = new ArrayList<>();
    private LinearLayout weixinly,zhifubaoly,allly;
    private CheckBox cb_wx,cb_zfb;
    private String paytype="1";//支付方式
    private int buytype = 0;//购买方式
    private IWXAPI api;
    private EditText dailicitytv;
    private int canbehehuorennum=2;
    private String citystr="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chengshihehuorenbuybike);
//        String area_str3 = FileUtil.readAssets(this, "area3.json");
//        Type listType = new TypeToken<ArrayList<Cityselectbean>>() {
//        }.getType();
//        Gson gson = new Gson();
//        citylistall = gson.fromJson(area_str3, listType);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        initView();
        getMsg2();
        settixiannewDialog();
        initlistener();

    }

    private void initlistener() {
        cb_wx.setClickable(false);
        cb_zfb.setClickable(false);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                buytype = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(position)).getPayTypeId();
                if (buytype==3)
                {
                    allly.setVisibility(View.GONE);
                }else {
                    allly.setVisibility(View.VISIBLE);
                }
                moneycount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(position)).getMoney();
                yiquancount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(position)).getYiQuan();
                adapter2.setchecked(position);
                setmoneytotal();
            }
        });
        textView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isNullorEmpty(citystr))
                {
                    toastShow("请选择你想要代理的区域");
                }else{
                    jubaodialog.show();
                }
            }
        });
//        showpop();
        xuanzechengshily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                popupWindow.showAsDropDown(xuanzechengshily, 0, -Util.dp2px(ChengshihehuorenbuybikeActivity.this, 1));
            }
        });
        weixinly.setOnClickListener(this);
        zhifubaoly.setOnClickListener(this);
        dailicitytv.setOnClickListener(this);
        tv_agreement.setOnClickListener(this);
    }

    private void initView() {
        allly= (LinearLayout) findViewById(R.id.zhifulyly);
        weixinly= (LinearLayout) findViewById(R.id.wxly);
        zhifubaoly= (LinearLayout) findViewById(R.id.zfbly);
        cb_wx= (CheckBox) findViewById(R.id.cb_chongzhi_wx);
        cb_zfb= (CheckBox) findViewById(R.id.cb_chongzhi_zfb);
        dailicitytv= (EditText) findViewById(R.id.dailicitytv);
        xuanzechengshily = (RelativeLayout) findViewById(R.id.xuanzechengshily);
        textView2 = (TextView) findViewById(R.id.textView2);
        gv = (MyGridListView) findViewById(R.id.jiagegv);
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("认购单车");
        total_pricetv = (TextView) findViewById(R.id.total_pricetv);
        tv_agreement= (TextView) findViewById(R.id.tv_agreement);
    }

    /**
     * //获取商品支付方式
     */
    private void getMsg2() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        addSubscription(apiStores.ProductPayType(params),
                new ApiCallback<ProductPayTypeResult>() {
                    @Override
                    public void onSuccess(ProductPayTypeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            chuandiProductPayTypeResult = model;
                            payTypeslist.clear();
//                            .memoryPolicy(MemoryPolicy.NO_CACHE,MemoryPolicy.NO_STORE)
                            //  Picasso.with(RengouActivity.this).load(model.getData().getProductImg()).error(R.drawable.zhanweitu).placeholder(R.drawable.zhanweitu).into(buydancheiv);
                            payTypeslist = (ArrayList<ProductPayTypeResult.DataBean.PayTypesBean>) model.getData().getPayTypes();
                            //   payTypeslist.addAll(payTypeslist);
                            adapter2 = new BuydanchetypeAdapter2(ChengshihehuorenbuybikeActivity.this, payTypeslist);
                            gv.setAdapter(adapter2);
                            setoncheck();
                        } else {
                            toastShow(model.getMessage());
                        }

                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                    }
                });
    }

    private void setoncheck() {
        if (payTypeslist != null && payTypeslist.size() > 0) {
            buytype = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(0)).getPayTypeId();
            moneycount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(0)).getMoney();
            yiquancount = ((ProductPayTypeResult.DataBean.PayTypesBean) adapter2.getItem(0)).getYiQuan();
            adapter2.setchecked(0);
            setmoneytotal();
        }
    }

    private void setmoneytotal() {
//        total_pricetv.setText("￥"+(Double) (sellingnum*moneycount));
        if (yiquancount != 0 && moneycount == 0) {
            total_pricetv.setText("翼券" + canbehehuorennum * yiquancount);
        } else if (yiquancount != 0 && moneycount != 0) {
//            total_pricetv.setText("￥"+df.format((Double) (sellingnum*moneycount))+"+"+"翼券"+sellingnum*yiquancount);
            total_pricetv.setText("￥" + (Double) (canbehehuorennum * moneycount) + "+" + "翼券" + canbehehuorennum * yiquancount);
            // holder.tv.setText("￥"+1111+"+"+"翼券"+100);
        } else {
//            total_pricetv.setText("￥"+df.format((Double) (sellingnum*moneycount)));
            total_pricetv.setText("￥" + (Double) (canbehehuorennum * moneycount));
        }
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
    private void zhifu() {
        if (buytype == 3 && yiquancount != 0 && moneycount == 0)//翼券支付
        {
            Map<String, String> params = new HashMap<>();
            params.put("token", preferences.getString("token", ""));
            params.put("typeId", buytype + "");
            params.put("count", canbehehuorennum + "");
            params.put("cityLocation",citystr);
            showProgressDialog();
            addSubscription(apiStores.YiBuyBicycle(params),
                    new ApiCallback<YiBuyBicycleResult>() {
                        @Override
                        public void onSuccess(YiBuyBicycleResult model) {
                            if (model.getStatus() == Config.SUCCESSCODE) {
                                paysuccess();
                            } else {
                                toastShow(model.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            toastShow(msg);

                        }

                        @Override
                        public void onFinish() {
                            dismissProgressDialog();
                        }
                    });
        } else {//现金支付
            Map<String, String> params = new HashMap<>();
            params.put("token", preferences.getString("token", ""));
            params.put("typeId", buytype + "");
            params.put("count", canbehehuorennum + "");
            params.put("cityLocation",citystr);

            Log.e("token", preferences.getString("token", ""));
            Log.e("typeId", buytype + "");
            Log.e("count", canbehehuorennum + "");
            Log.e("cityLocation",citystr);

            showProgressDialog();
            addSubscription(apiStores.YiBuyBicycle(params),
                    new ApiCallback<YiBuyBicycleResult>() {

                        @Override
                        public void onSuccess(YiBuyBicycleResult model) {
                            if (model.getStatus() == Config.SUCCESSCODE) {
//                            paysuccess();
                                if (paytype.equals("2")) {//支付宝
                                    zfbpay(model.getData().getAlipay());
                                } else {
//                                model.getData().getWeChatPay();
//                                model.getData().getWeChat();
                                    wxpay(model.getData().getWeChatPay());
                                }
                            } else {
                                toastShow(model.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            toastShow(msg);

                        }

                        @Override
                        public void onFinish() {
                            dismissProgressDialog();
//                        paysuccess();
//                        String zfb="\"app_id=2017041206669129&biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%22%E8%B4%AD%E4%B9%B0%E7%BF%BC%E5%88%B8%22%2C%22body%22%3A%22%E8%B4%AD%E4%B9%B0%E7%BF%BC%E5%88%B8%22%2C%22out_trade_no%22%3A%22ceb6a7d57b5a11e7ae1293349ff1e13c%22%7D&charset=utf-8&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F47.93.46.52%3A8765%2FPayment%2FAlipayCallBack&sign=PgzwsQl81CDxu%2Bo4oJUaoe6qGCGfC7esIDm2OTteeI5i5oGiI%2FRuu%2F5z2EbGsZvaTYzz74ZAF6IHEHqu4hoDEnDwiXp09Oaalh4PUOUOb77ga4vJ4%2Faw8qwc5TKmfm7J%2B%2BKqjjDEyerRNdk7TtLThr9NsH2d3LgrqcMpWiPrY9c%3D&sign_type=RSA&timestamp=2017-08-07+18%3A26%3A02&version=1.0\"";
//                        zfbpay(zfb);
                        }
                    });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==200&&resultCode==1)
        {
            dailicitytv.setText(data.getStringExtra("cityname"));
            citystr=data.getStringExtra("cityname");
        }
    }

    @Override
    protected void onDestroy() {
//        if (popupWindow!=null)
//        {
//            popupWindow.dismiss();
//        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    private void paysuccess() {
//        toastShow("ok");
        EventBus.getDefault().post("hehuorenbuyok");
        Intent i=new Intent(ChengshihehuorenbuybikeActivity.this,ChengshihehuorenActivity.class);
        startActivityForResult(i,200);
        setResult(101);
        finish();
//        setResult(1);
//        EventBus.getDefault().post("buybikeok");
//        jubaodialog.show();
//        intent.putExtra("payamont",payamont);
//        startActivityForResult(intent,400);

    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.dailicitytv:
                Intent i=new Intent(ChengshihehuorenbuybikeActivity.this,CityoActivity.class);
                startActivityForResult(i,200);
                break;
            case R.id.wxly:
                cb_zfb.setChecked(false);
                cb_wx.setChecked(true);
                paytype="1";
                break;
            case R.id.zfbly:
                cb_zfb.setChecked(true);
                cb_wx.setChecked(false);
                paytype="2";
                break;
            case R.id.tv_agreement:
                getWZMsg("11","城市合伙人协议");
                break;
        }
    }

    private void wxpay(YiBuyBicycleResult.DataBean.WeChatPayBean model) {
        api.registerApp(model.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            Toast.makeText(ChengshihehuorenbuybikeActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(ChengshihehuorenbuybikeActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {
            PayReq request = new PayReq();

            request.appId = model.getAppId();

            request.partnerId = model.getPartnerId();

            request.prepayId = model.getPrepayId();

            request.packageValue = model.getPackageX();

            request.nonceStr = model.getNoncestr();

            request.timeStamp = model.getTimestamp();

            request.sign = model.getSign();

            api.sendReq(request);

        } catch (Exception e) {
            Toast.makeText(ChengshihehuorenbuybikeActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if (progress == 0) {//支付成功
            paysuccess();
        } else {
            Toast.makeText(ChengshihehuorenbuybikeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void zfbpay(final String orderinfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ChengshihehuorenbuybikeActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ChengshihehuorenbuybikeActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    //对话框1
    Dialog jubaodialog;
    private void settixiannewDialog() {
        TextView tixiandialogquxiao, tixiandialogqueding, note1,note2;
        ImageView xuzhi;
        LayoutInflater inflater = LayoutInflater.from(ChengshihehuorenbuybikeActivity.this);
        final View headview = inflater.inflate(R.layout.tixiantishi_dialog, null, false);
        tixiandialogquxiao = headview.findViewById(R.id.tixiandialogquxiao);
        tixiandialogqueding = headview.findViewById(R.id.tixiandialogqueding);
        note2 = headview.findViewById(R.id.note2);
        xuzhi= headview.findViewById(R.id.xuzhi);
        note1= headview.findViewById(R.id.notes);
//        note1.setVisibility(View.GONE);
        xuzhi.setVisibility(View.GONE);
        note2.setText("您确定购买单车成为城市合伙人吗?");
        jubaodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        jubaodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        jubaodialog.setCanceledOnTouchOutside(false);
        Window dialogWindow = jubaodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = (int) (DataSingle.getInstance().PhoneW * 0.75); // 宽度
//        lp.height = (int) (DataSingle.getInstance().PhoneW * 0.75);
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        tixiandialogquxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
            }
        });
        tixiandialogqueding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                zhifu();
            }
        });
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        jubaodialog.setOnKeyListener(keylistener);
    }
    private void getWZMsg(String type, final String name) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", type);
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(ChengshihehuorenbuybikeActivity.this, TotalWebActivity.class);
                            i.putExtra("title", name);
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    /******

     PopupWindow popupWindow;
     //    RecyclerView myrecycle1;
     //    LinearLayoutManager mLayoutManager;
     //    MyrecyAdapter1 mAdapter;
     MTagFlowLayout id_flowlayout, id_flowlayout2, id_flowlayout3, id_flowlayout4;
     TagFlowLayout id_flowlayout5;
     ArrayList<String> mVals, mVals2, mVals3, mVals4, curshilist;
     MTagAdapter<String> adapter1, adapter22, adapter33, adapter44;
     TagAdapter adapter9999;
     String sheng1, shi1;
     ScrollView sr;
     private TextView shengtvtv,shitvtv;
     private void showpop() {
     View popupWindowView = getLayoutInflater().inflate(R.layout.pop_selectcity, null);
     popupWindow = new PopupWindow(popupWindowView, WindowManager.LayoutParams.MATCH_PARENT,
     WindowManager.LayoutParams.WRAP_CONTENT);
     id_flowlayout =  popupWindowView.findViewById(R.id.id_flowlayout);
     id_flowlayout2 = popupWindowView.findViewById(R.id.id_flowlayout2);
     id_flowlayout3 =  popupWindowView.findViewById(R.id.id_flowlayout3);
     id_flowlayout4 =  popupWindowView.findViewById(R.id.id_flowlayout4);
     id_flowlayout5 =  popupWindowView.findViewById(R.id.id_flowlayout5);
     shengtvtv=popupWindowView.findViewById(R.id.shengfentvtv);
     shitvtv=popupWindowView.findViewById(R.id.chengshitvtv);
     sr = (ScrollView) popupWindowView.findViewById(R.id.sr);
     mVals = new ArrayList<>();
     for (int i = 0; i < citylistall.get(0).getKey().getList().size(); i++) {
     mVals.add(citylistall.get(0).getKey().getList().get(i).getProvinceName());
     }
     adapter1 = new MTagAdapter<String>(mVals) {
    @Override
    public View getView(FlowLayout parent, int position, String s) {
    TextView tv = (TextView) View.inflate(ChengshihehuorenbuybikeActivity.this, R.layout.tv, null);
    tv.setText(s);
    return tv;
    }
    };
     id_flowlayout.setAdapter(adapter1);
     mVals2 = new ArrayList<>();
     for (int i = 0; i < citylistall.get(1).getKey().getList().size(); i++) {
     mVals2.add(citylistall.get(1).getKey().getList().get(i).getProvinceName());
     }
     adapter22 = new MTagAdapter<String>(mVals2) {
    @Override
    public View getView(FlowLayout parent, int position, String s) {
    TextView tv = (TextView) View.inflate(ChengshihehuorenbuybikeActivity.this, R.layout.tv, null);
    tv.setText(s);
    return tv;
    }
    };
     id_flowlayout2.setAdapter(adapter22);

     mVals3 = new ArrayList<>();
     for (int i = 0; i < citylistall.get(2).getKey().getList().size(); i++) {
     mVals3.add(citylistall.get(2).getKey().getList().get(i).getProvinceName());
     }
     adapter33 = new MTagAdapter<String>(mVals3) {
    @Override
    public View getView(FlowLayout parent, int position, String s) {
    TextView tv = (TextView) View.inflate(ChengshihehuorenbuybikeActivity.this, R.layout.tv, null);
    tv.setText(s);
    return tv;
    }
    };
     id_flowlayout3.setAdapter(adapter33);

     mVals4 = new ArrayList<>();
     for (int i = 0; i < citylistall.get(3).getKey().getList().size(); i++) {
     mVals4.add(citylistall.get(3).getKey().getList().get(i).getProvinceName());
     }
     adapter44 = new MTagAdapter<String>(mVals4) {
    @Override
    public View getView(FlowLayout parent, int position, String s) {
    TextView tv = (TextView) View.inflate(ChengshihehuorenbuybikeActivity.this, R.layout.tv, null);
    tv.setText(s);
    return tv;
    }
    };
     id_flowlayout4.setAdapter(adapter44);
     id_flowlayout.setOnTagClickListener(new MTagFlowLayout.OnTagClickListener() {
    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
    sheng1 = mVals.get(position);
    curshilist = new ArrayList<String>();
    for (int i = 0; i < citylistall.get(0).getKey().getList().get(position).getCities().size(); i++) {
    curshilist.add(citylistall.get(0).getKey().getList().get(position).getCities().get(i).getCityName());
    }
    setcityshi(curshilist, id_flowlayout5);
    adapter22.clearList();
    adapter33.clearList();
    adapter44.clearList();
    adapter1.setSelectedList(position);
    return true;
    }
    });
     id_flowlayout2.setOnTagClickListener(new MTagFlowLayout.OnTagClickListener() {
    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
    sheng1 = mVals2.get(position);
    curshilist = new ArrayList<String>();
    for (int i = 0; i < citylistall.get(1).getKey().getList().get(position).getCities().size(); i++) {
    curshilist.add(citylistall.get(1).getKey().getList().get(position).getCities().get(i).getCityName());
    }
    setcityshi(curshilist, id_flowlayout5);
    adapter1.clearList();
    adapter33.clearList();
    adapter44.clearList();
    adapter22.setSelectedList(position);
    return true;
    }
    });
     id_flowlayout3.setOnTagClickListener(new MTagFlowLayout.OnTagClickListener() {
    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
    sheng1 = mVals3.get(position);
    curshilist = new ArrayList<String>();
    for (int i = 0; i < citylistall.get(2).getKey().getList().get(position).getCities().size(); i++) {
    curshilist.add(citylistall.get(2).getKey().getList().get(position).getCities().get(i).getCityName());
    }
    setcityshi(curshilist, id_flowlayout5);
    adapter1.clearList();
    adapter22.clearList();
    adapter44.clearList();
    adapter33.setSelectedList(position);
    //                adapter44.setSelectedList(-1);
    return true;
    }
    });
     id_flowlayout4.setOnTagClickListener(new MTagFlowLayout.OnTagClickListener() {
    @Override
    public boolean onTagClick(View view, int position, FlowLayout parent) {
    sheng1 = mVals4.get(position);
    curshilist = new ArrayList<String>();
    for (int i = 0; i < citylistall.get(3).getKey().getList().get(position).getCities().size(); i++) {
    curshilist.add(citylistall.get(3).getKey().getList().get(position).getCities().get(i).getCityName());
    }
    setcityshi(curshilist, id_flowlayout5);
    adapter1.clearList();
    adapter22.clearList();
    adapter33.clearList();
    adapter44.setSelectedList(position);
    //                adapter44.setSelectedList(position);
    return true;
    }
    });
     //        myrecycle1=popupWindowView.findViewById(R.id.myrecycle1);
     //        //创建线性布局
     //        mLayoutManager = new LinearLayoutManager(this);
     //        //垂直方向
     //        mLayoutManager.setOrientation(OrientationHelper.VERTICAL);
     //        //给RecyclerView设置布局管理器
     //        myrecycle1.setLayoutManager(mLayoutManager);
     //        //创建适配器，并且设置
     //        mAdapter = new MyrecyAdapter1(citylistall,this);
     //        myrecycle1.setAdapter(mAdapter);
     // 设置允许在外点击消失
     shengtvtv.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    if (TextUtils.isNullorEmpty(shi1))
    {
    sr.setVisibility(View.VISIBLE);
    }else{
    sr.setVisibility(View.VISIBLE);
    }
    //                android:textColor="@color/radio_button_selected_color"
    shengtvtv.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
    shengtvtv.setBackgroundColor(getResources().getColor(R.color.bg_main_white));
    shitvtv.setTextColor(getResources().getColor(R.color.text_main_6));
    shitvtv.setBackgroundColor(getResources().getColor(R.color.div_total_color));
    }
    });
     shitvtv.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    if (TextUtils.isNullorEmpty(sheng1))
    {
    toastShow("请先选择省份");
    }else if (curshilist!=null&&curshilist.size()<=1)
    {
    toastShow("此地区为省市一体区");
    }else {
    sr.setVisibility(View.INVISIBLE);
    shitvtv.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
    shitvtv.setBackgroundColor(getResources().getColor(R.color.bg_main_white));
    shengtvtv.setTextColor(getResources().getColor(R.color.text_main_6));
    shengtvtv.setBackgroundColor(getResources().getColor(R.color.div_total_color));
    }
    }
    });
     popupWindow.setFocusable(false);
     popupWindow.setOutsideTouchable(false);
     // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
     popupWindow.setBackgroundDrawable(new BitmapDrawable());
     DisplayMetrics metric = new DisplayMetrics();
     getWindowManager().getDefaultDisplay().getMetrics(metric);
     int width = metric.widthPixels;     // 屏幕宽度（像素）
     int pos = width - popupWindow.getWidth();
     popupWindow.setWidth(DataSingle.getInstance().PhoneW - Util.dp2px(this, 30));
     popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
    @Override
    public void onDismiss() {
    backgroundAlpha(1f);
    setcitynametextview();
    }
    });
     }
     @Override
     public boolean dispatchTouchEvent(MotionEvent event){
     if(popupWindow!=null&&popupWindow.isShowing()){
     return false;
     }
     return super.dispatchTouchEvent(event);
     }
     private void setcitynametextview(){
     dailicitytv.setText((sheng1+shi1).trim());
     }
     private void setcityshi(final ArrayList<String> list, TagFlowLayout view) {
     if (list.size() <= 1) {
     shi1="";
     popupWindow.dismiss();
     } else {
     sr.setVisibility(View.INVISIBLE);
     shitvtv.setTextColor(getResources().getColor(R.color.radio_button_selected_color));
     shitvtv.setBackgroundColor(getResources().getColor(R.color.bg_main_white));
     shengtvtv.setTextColor(getResources().getColor(R.color.text_main_6));
     shengtvtv.setBackgroundColor(getResources().getColor(R.color.div_total_color));
     adapter9999= new TagAdapter<String>(list) {
     @Override
     public View getView(FlowLayout parent, int position, String s) {
     TextView tv = (TextView) View.inflate(ChengshihehuorenbuybikeActivity.this, R.layout.tv, null);
     tv.setText(s);
     return tv;
     }
     };
     view.setAdapter(adapter9999);
     adapter9999.notifyDataChanged();
     view.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
     @Override
     public boolean onTagClick(View view, int position, FlowLayout parent) {
     shi1 = list.get(position);
     popupWindow.dismiss();
     adapter9999.setSelectedList(position);
     return true;
     }
     });
     }
     }
     */
}
